#############################################################
# File: DelfineMesh.py
# Function: Creates mesh for dolfin use
# Author: Bruno Luna
# Date: 04/04/11
# Modifications Date:
# 06/04/11 : Modified to read, convert and search for errors also for the gmsh and xml cases
#
#
#
#
#############################################################
from dolfin import *
import sys
import os

class DelfineMesh:
    """Creates mesh for dolfin use."""  
    
    def __init__(self, parameter): 
        # Reads the type of mesh (generated by dolfin or by external program)
        meshType = parameter.geom.mesh.type
        
        # Dolfin generated meshes
        if (meshType == "dolfin-generated"):
            dolfinGenType = parameter.geom.mesh.dolfinGen.type
            n = parameter.geom.mesh.dolfinGen.n
            if (dolfinGenType == "UnitInterval"):
                mesh = UnitInterval(n[0])
            elif (dolfinGenType == "UnitSquare"):
                mesh = UnitSquare(n[0], n[1], 'crossed') # crossed edges used to avoid mesh orientation efffect
            elif (dolfinGenType == "UnitCube"):
                mesh = UnitCube(n[0], n[1],  n[2])
            elif (dolfinGenType == "UnitCircle"):
                mesh = UnitCircle(n[0])
            elif (dolfinGenType == "Rectangle"):
                p0 =  parameter.geom.mesh.dolfinGen.p0
                p1 =  parameter.geom.mesh.dolfinGen.p1
                mesh = Rectangle(p0[0], p0[1],  p1[0], p1[1], n[0], n[1])
            self.allData = mesh
        
        # Mesh generated by gmsh and converted to dolfin .xml format
        elif (meshType == "gmsh"):
            cmd = './Src/Utils/delfine-convert '+ './CaseFiles/' + parameter.geom.mesh.filename + ' ./CaseFiles/meshFile.xml'
            # Execute conversion of *.MSH and read *.XML file
            try:
                os.system(cmd)
                mesh = Mesh('./CaseFiles/meshFile.xml')
                self.allData = mesh
            except Exception, inst:
                print "Error(5):"   
                print "Unexpected error opening %s: %s" % (parameter.geom.mesh.filename, inst)
                print " "
                sys.exit(1)
       
       # Mesh already available as dolfin .xml format
        elif (meshType == "xml"):
            # Read *.XML file
            try:
                mesh = Mesh('./CaseFiles/' + parameter.geom.mesh.filename)
                self.allData = mesh
            except Exception, inst:
                print "Error(6):"
                print "Unexpected error opening %s: %s" % (parameter.geom.mesh.filename, inst)
                print " "
                sys.exit(1)
#############################################################
